<template>
  <div class="h-full">
    <SearchCom
      :searchList="searchConfig"
      @search="handleSearch"
      @reset="handleReset"
    />
    <div class="table-container">
      <!-- 操作按钮 -->
      <!-- <div class="operation-bar">
        <el-button type="primary" @click="handleAdd">新增会员</el-button>
      </div> -->
      
      <el-table :data="tableData" style="width: 100%" border class="cover-table">
        <el-table-column prop="title" label="会员信息" min-width="250">
          <template #default="scope">
            <div class="flex">
              <el-popover placement="right" width="226" trigger="hover">
                <div
                  class="bigImg"
                  :style="{
                    backgroundImage: `url(${scope.row.avatar})`,
                  }"
                ></div>
                <template #reference>
                  <div
                    class="goodImg"
                    :style="{
                      backgroundImage: `url(${scope.row.avatar})`,
                    }"
                  ></div>
                </template>
              </el-popover>

              <div class="ml10 flex_fdc_jcsb text-left">
                <div class="color-333333 line-2">{{ scope.row.nickname }}</div>
                <div>ID: {{ scope.row.id }}</div>
                <div>注册时间: {{ scope.row.registerTime }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="基本信息" min-width="200">
          <template #default="scope">
            <div>姓名: {{ scope.row.name }}</div>
            <div>性别: {{ scope.row.gender === 'male' ? '男' : scope.row.gender === 'female' ? '女' : '未知' }}</div>
            <div>生日: {{ scope.row.birthday }}</div>
            <div>手机: {{ scope.row.phone }}</div>
          </template>
        </el-table-column>
        
        <el-table-column label="推荐信息" min-width="200">
          <template #default="scope">
            <div>推荐人: {{ scope.row.referrer ? scope.row.referrer.name : '无' }}</div>
            <div>推荐用户量: {{ scope.row.referralCount }}人</div>
            <el-popover
              v-if="scope.row.referralCount > 0"
              placement="top" 
              width="300" 
              trigger="hover"
            >
              <template #default>
                <div>
                  <div><strong>推荐用户列表:</strong></div>
                  <el-table :data="scope.row.referrals" style="width: 100%">
                    <el-table-column prop="name" label="昵称" width="120" />
                    <el-table-column prop="time" label="注册时间" width="160" />
                  </el-table>
                </div>
              </template>
              <template #reference>
                <el-button link type="primary">查看推荐用户</el-button>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        
        <el-table-column label="消费数据" min-width="240">
          <template #default="scope">
            <div>消费总金额: {{ scope.row.totalConsumption }}元</div>
            <div>总积分: {{ scope.row.totalPoints }}</div>
            <div>积分消费总额: {{ scope.row.pointsUsed }}</div>
            <div>剩余积分: {{ scope.row.remainingPoints }}</div>
            <el-popover placement="top" width="300" trigger="hover">
              <template #default>
                <div>
                  <div><strong>最近消费记录:</strong></div>
                  <el-table :data="scope.row.recentTransactions" style="width: 100%">
                    <el-table-column prop="date" label="日期" width="100" />
                    <el-table-column prop="amount" label="金额" width="80" />
                    <el-table-column prop="type" label="类型" width="100" />
                  </el-table>
                </div>
              </template>
              <template #reference>
                <el-button link type="primary">查看消费记录</el-button>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        
        <!-- <el-table-column prop="level" label="会员等级" width="120">
          <template #default="scope">
            <el-tag :type="getLevelType(scope.row.level)">
              {{ scope.row.level }}
            </el-tag>
          </template>
        </el-table-column> -->
        
        <!-- <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">
              {{ scope.row.status === '1' ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column> -->
        
        <el-table-column fixed="right" label="操作" width="160">
          <template #default="scope">
            <!-- <el-button 
              link 
              type="primary" 
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button> -->
            <el-button 
              link 
              type="primary" 
              @click="handleViewDetail(scope.row)"
            >
              详情
            </el-button>
            <!-- <el-popconfirm
              title="确定要删除该会员吗？"
              @confirm="handleDelete(scope.row)"
            >
              <template #reference>
                <el-button link type="danger">删除</el-button>
              </template>
            </el-popconfirm> -->
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 编辑/新增会员对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentEditData ? '编辑会员' : '新增会员'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="会员昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入会员昵称" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
            <el-radio label="unknown">未知</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker
            v-model="form.birthday"
            type="date"
            placeholder="选择出生日期"
            style="width: 100%"
          />
        </el-form-item>
        <!-- <el-form-item label="会员等级">
          <el-select v-model="form.level" placeholder="请选择会员等级">
            <el-option label="普通会员" value="普通会员" />
            <el-option label="银卡会员" value="银卡会员" />
            <el-option label="金卡会员" value="金卡会员" />
            <el-option label="钻石会员" value="钻石会员" />
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="1">正常</el-radio>
            <el-radio label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 会员详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="会员详情"
      width="800px"
    >
      <div v-if="currentDetailData" class="member-detail">
        <div class="member-header">
          <div class="member-avatar" :style="{backgroundImage: `url(${currentDetailData.avatar})`}"></div>
          <div class="member-info">
            <h2>{{ currentDetailData.nickname }}</h2>
            <div>会员ID: {{ currentDetailData.id }}</div>
            <!-- <div>会员等级: {{ currentDetailData.level }}</div> -->
            <!-- <div>状态: {{ currentDetailData.status === '1' ? '正常' : '禁用' }}</div> -->
          </div>
        </div>
        
        <el-divider content-position="left">基本信息</el-divider>
        <div class="detail-section">
          <div class="detail-item">
            <span class="item-label">姓名:</span>
            <span>{{ currentDetailData.name }}</span>
          </div>
          <div class="detail-item">
            <span class="item-label">性别:</span>
            <span>{{ currentDetailData.gender === 'male' ? '男' : currentDetailData.gender === 'female' ? '女' : '未知' }}</span>
          </div>
          <div class="detail-item">
            <span class="item-label">生日:</span>
            <span>{{ currentDetailData.birthday }}</span>
          </div>
          <div class="detail-item">
            <span class="item-label">手机号码:</span>
            <span>{{ currentDetailData.phone }}</span>
          </div>
          <div class="detail-item">
            <span class="item-label">注册时间:</span>
            <span>{{ currentDetailData.registerTime }}</span>
          </div>
        </div>
        
        <el-divider content-position="left">积分与消费</el-divider>
        <div class="detail-section">
          <div class="detail-item">
            <span class="item-label">消费总金额:</span>
            <span>{{ currentDetailData.totalConsumption }}元</span>
          </div>
          <div class="detail-item">
            <span class="item-label">总积分:</span>
            <span>{{ currentDetailData.totalPoints }}</span>
          </div>
          <div class="detail-item">
            <span class="item-label">积分消费总额:</span>
            <span>{{ currentDetailData.pointsUsed }}</span>
          </div>
          <div class="detail-item">
            <span class="item-label">剩余积分:</span>
            <span>{{ currentDetailData.remainingPoints }}</span>
          </div>
        </div>
        
        <el-divider content-position="left">消费记录</el-divider>
        <el-table :data="currentDetailData.recentTransactions" style="width: 100%">
          <el-table-column prop="date" label="日期" width="160" />
          <el-table-column prop="amount" label="金额" width="120" />
          <el-table-column prop="points" label="积分变动" width="120" />
          <el-table-column prop="type" label="类型" width="120" />
          <el-table-column prop="description" label="描述" />
        </el-table>
        
        <el-divider content-position="left">推荐信息</el-divider>
        <div class="detail-section">
          <div class="detail-item">
            <span class="item-label">推荐人:</span>
            <span>{{ currentDetailData.referrer ? currentDetailData.referrer.name : '无' }}</span>
          </div>
          <div class="detail-item">
            <span class="item-label">推荐用户量:</span>
            <span>{{ currentDetailData.referralCount }}人</span>
          </div>
        </div>
        
        <el-table v-if="currentDetailData.referrals && currentDetailData.referrals.length > 0" 
                 :data="currentDetailData.referrals" style="width: 100%">
          <el-table-column prop="name" label="昵称" width="120" />
          <el-table-column prop="time" label="注册时间" width="160" />
          <el-table-column prop="consumption" label="消费金额" width="120" />
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import SearchCom from "@/components/SearchCom.vue";
import { ElMessage, ElMessageBox } from 'element-plus';

// 搜索配置
const searchConfig = ref([
  {
    label: "用户昵称",
    key: "nickname",
    type: "input",
  },
  {
    label: "手机号码",
    key: "phone",
    type: "input",
  },
  {
    label: "姓名",
    key: "name",
    type: "input",
  },
//   {
//     label: "会员等级",
//     key: "level",
//     type: "select",
//     options: [
//       { label: "普通会员", value: "普通会员" },
//       { label: "银卡会员", value: "银卡会员" },
//       { label: "金卡会员", value: "金卡会员" },
//       { label: "钻石会员", value: "钻石会员" },
//     ],
//   },
  {
    label: "注册时间",
    key: "registerTime",
    type: "daterange",
    dateType: "daterange",
  },
]);

// 分页相关数据
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);

// 模拟表格数据
const tableData = ref(
  Array.from({ length: 10 }, (_, index) => ({
    id: 10000 + index,
    nickname: `用户${index + 1}`,
    name: `张${index + 1}`,
    gender: ['male', 'female', 'unknown'][index % 3],
    birthday: `199${index % 10}-${(index % 12 + 1).toString().padStart(2, '0')}-${(index % 28 + 1).toString().padStart(2, '0')}`,
    phone: `1391234${index.toString().padStart(4, '0')}`,
    avatar: `https://randomuser.me/api/portraits/${index % 2 ? 'women' : 'men'}/${index + 1}.jpg`,
    registerTime: `2023-${(index % 12 + 1).toString().padStart(2, '0')}-${(index % 28 + 1).toString().padStart(2, '0')}`,
    level: ['普通会员', '银卡会员', '金卡会员', '钻石会员'][index % 4],
    totalConsumption: (Math.random() * 10000 + 1000).toFixed(2),
    totalPoints: Math.floor(Math.random() * 5000 + 500),
    pointsUsed: Math.floor(Math.random() * 1000),
    remainingPoints: Math.floor(Math.random() * 4000 + 100),
    referralCount: Math.floor(Math.random() * 5),
    referrer: index % 3 === 0 ? null : {
      id: 10000 - index - 1,
      name: `推荐人${index}`,
      phone: `1387654${index.toString().padStart(4, '0')}`
    },
    referrals: Array.from({ length: index % 5 }, (_, i) => ({
      id: 20000 + i,
      name: `被推荐用户${i + 1}`,
      time: `2023-${((index + i) % 12 + 1).toString().padStart(2, '0')}-${((index + i) % 28 + 1).toString().padStart(2, '0')}`,
      consumption: (Math.random() * 1000 + 100).toFixed(2)
    })),
    recentTransactions: Array.from({ length: 5 }, (_, i) => ({
      date: `2023-${((index + i) % 12 + 1).toString().padStart(2, '0')}-${((index + i) % 28 + 1).toString().padStart(2, '0')}`,
      amount: (Math.random() * 500 + 10).toFixed(2),
      type: ['消费', '退款', '充值'][i % 3],
      points: i % 3 === 0 ? `-${Math.floor(Math.random() * 100)}` : `+${Math.floor(Math.random() * 100)}`,
      description: ['购买商品', '订单退款', '会员充值'][i % 3]
    })),
    status: index % 5 === 0 ? "2" : "1", // 大部分为正常状态
  }))
);

// 对话框显示状态
const dialogVisible = ref(false);
const detailDialogVisible = ref(false);

// 当前编辑的数据
const currentEditData = ref(null);
const currentDetailData = ref(null);

// 表单数据
const form = ref({
  nickname: '',
  name: '',
  phone: '',
  gender: 'unknown',
  birthday: '',
  level: '普通会员',
  status: '1'
});

// 表单验证规则
const rules = {
  nickname: [
    { required: true, message: '请输入会员昵称', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
};

const formRef = ref(null);

// 处理搜索
const handleSearch = (formData) => {
  console.log("搜索条件:", formData);
  // 实际项目中这里应该调用API进行搜索
  ElMessage.success('搜索请求已发送');
};

// 处理重置
const handleReset = () => {
  console.log("表单已重置");
  // 重置后可能需要重新加载初始数据
  ElMessage.info('表单已重置');
};

// 新增会员
const handleAdd = () => {
  currentEditData.value = null; // 置空编辑数据，表示新增
  form.value = {
    nickname: '',
    name: '',
    phone: '',
    gender: 'unknown',
    birthday: '',
    level: '普通会员',
    status: '1'
  };
  dialogVisible.value = true; // 显示对话框
};

// 编辑会员
const handleEdit = (row) => {
  currentEditData.value = { ...row }; // 设置当前编辑的数据
  form.value = {
    id: row.id,
    nickname: row.nickname,
    name: row.name,
    phone: row.phone,
    gender: row.gender,
    birthday: row.birthday,
    level: row.level,
    status: row.status
  };
  dialogVisible.value = true; // 显示对话框
};

// 查看会员详情
const handleViewDetail = (row) => {
  currentDetailData.value = { ...row };
  detailDialogVisible.value = true;
};

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (currentEditData.value) {
        // 编辑模式
        const index = tableData.value.findIndex(item => item.id === form.value.id);
        if (index !== -1) {
          tableData.value[index] = {
            ...tableData.value[index],
            ...form.value
          };
          ElMessage.success(`会员: ${form.value.nickname} 已更新`);
        }
      } else {
        // 新增模式
        const newId = Math.max(...tableData.value.map(item => item.id), 0) + 1;
        const newMember = {
          ...form.value,
          id: newId,
          avatar: 'https://randomuser.me/api/portraits/men/1.jpg',
          registerTime: new Date().toISOString().split('T')[0],
          totalConsumption: '0.00',
          totalPoints: 0,
          pointsUsed: 0,
          remainingPoints: 0,
          referralCount: 0,
          referrals: [],
          recentTransactions: []
        };
        tableData.value.unshift(newMember);
        ElMessage.success(`会员: ${form.value.nickname} 已添加`);
      }
      dialogVisible.value = false;
    } else {
      return false;
    }
  });
};

// 删除会员
const handleDelete = (row) => {
  console.log("删除会员:", row);
  // 实际项目中这里应该调用API进行删除
  const index = tableData.value.findIndex(item => item.id === row.id);
  if (index !== -1) {
    tableData.value.splice(index, 1);
    ElMessage.success(`会员: ${row.nickname} 已删除`);
  }
};

// 处理页码变化
const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`);
  // 这里请求对应页的数据
};

// 处理每页数量变化
const handleSizeChange = (val) => {
  console.log(`每页 ${val} 条`);
  // 这里请求对应数量的数据
};

// 获取会员等级对应的标签类型
const getLevelType = (level) => {
  switch (level) {
    case '普通会员': return '';
    case '银卡会员': return 'info';
    case '金卡会员': return 'warning';
    case '钻石会员': return 'success';
    default: return '';
  }
};
</script>

<style scoped lang="scss">
.table-container {
  background-color: #fff;
  border-radius: 4px;
}

.goodImg {
  display: inline-block;
  flex-shrink: 0;
  width: 60px;
  height: 60px;
  overflow: hidden;
  border: 1px solid #e2e5f6;
  border-radius: 50%;
  background: #f8f8f8;
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
}

.bigImg {
  display: inline-block;
  flex-shrink: 0;
  width: 200px;
  height: 200px;
  overflow: hidden;
  border-radius: 4px;
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
}

.ml10 {
  margin-left: 10px;
}

.flex {
  display: flex;
}

.flex_fdc_jcsb {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.text-left {
  text-align: left;
}

.line-2 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.operation-bar {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-end;
}

/* 会员详情样式 */
.member-detail {
  padding: 10px;
}

.member-header {
  display: flex;
  margin-bottom: 20px;
}

.member-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-position: center;
  background-size: cover;
  margin-right: 20px;
}

.member-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.member-info h2 {
  margin-top: 0;
  margin-bottom: 10px;
}

.detail-section {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.detail-item {
  width: 50%;
  margin-bottom: 10px;
}

.item-label {
  font-weight: bold;
  margin-right: 5px;
}
</style>